package net.cloudsun.tree.random;

import net.cloudsun.tree.binary.BinaryNode;

import java.util.Random;

/**
 * @author Ryan
 * @since
 */
public class RandomNode<T> extends BinaryNode<T> {

    private static final Random RANDOM = new Random(System.currentTimeMillis());

    public RandomNode(T t) {
        super(t);
    }

    @Override
    public void add(BinaryNode<T> newNode) {
        BinaryNode<T> node = this;
        while (node.isFull()) {
            node = RANDOM.nextBoolean()? node.getLeft() : node.getRight();
        }

        if (node.isEmpty()) {
            if (RANDOM.nextBoolean()) {
                node.setLeft(newNode);
            } else {
                node.setRight(newNode);
            }
            return;
        }

        if (node.getLeft() == null) {
            node.setLeft(newNode);
        }else {
            node.setRight(newNode);
        }
    }
}
